﻿function Settings() {
    var self = this;
    this.name = ko.observable().extend({ required: "Please enter blog name" });
    this.tag = ko.observable();
    this.useImage = ko.observable(false);
    this.imageUrl = ko.observable();
    this.ga = ko.observable();
    this.postCount = ko.observable();
    this.moderation = ko.observable();
    this.timezone = ko.observable();
    this.skin = ko.observable();
    this.logFile = ko.observable();
    this.logLevel = ko.observable();
    this.registerUrl = ko.observable();
    this.showRegister = ko.computed(function () {
        return this.registerUrl() === '' ? false : true;
    }, this);
    this.shouldBackup = ko.observable();
    this.backupUrl = ko.observable();
    this.backupMessage = ko.observable();
    this.isBacking = ko.observable(false);

    this.generateUrl = ko.observable();
    this.generateMessage = ko.observable();
    this.isGenerating = ko.observable(false);

    this.postCountOptions = ko.observableArray();
    this.timezones = ko.observableArray();
    this.skins = ko.observableArray();

    this.successMessage = ko.observable();
    this.errors = ko.observableArray();
    this.errorMessage = ko.computed({
        read: function () {
            var html = '';
            if (this.errors().length > 0)
                html += this.errors()[0];
            if (this.errors().length > 1) {
                html += "<ul>"
                for (var idx = 1; idx < this.errors().length; idx++)
                    html += "<li>" + this.errors()[idx] + "</li>";
                html += "</ul>";
            }
            return html;
        },
        write: function (value) {
            this.errors.removeAll();
            this.errors.push(value);
        },
        owner: this
    });

    this.hasError = ko.computed(function () {
        return this.name.hasError();
    }, this);

    this.setError = function () {
        if (this.hasError()) {
            this.errorMessage("Please correct the following errors:");
            if (this.name.hasError())
                this.errors.push(this.name.validationMessage());
        } else {
            this.clearError();
        }
    }

    this.clearError = function () {
        this.errors.removeAll();
    }

    this.loadJson = function (data) {
        this.name(data.Settings.Name);
        this.tag(data.Settings.Tagline);
        this.useImage(data.Settings.UseImage);
        this.imageUrl(data.Settings.ImageUrl);
        this.ga(data.Settings.GATrackingCode);
        this.moderation(data.Settings.CommentModeration);

        this.timezones(this.getOptions(data.Timezones));
        this.skins(this.getOptions(data.Skins));
        this.postCountOptions(this.getOptions(data.PostCountOptions));
        this.registerUrl(data.RegisterUrl);
        this.backupUrl(data.BackupUrl);
        this.generateUrl(data.GenerateUrl);


        this.timezone(data.Settings.Timezone);
        this.skin(data.Settings.Skin);
        this.postCount(data.Settings.PostCount);
        this.logFile(data.Settings.LogFile);
        this.logLevel(data.Settings.LogLevel);
        this.shouldBackup(data.Settings.ShouldBackup);
    }

    this.update = function () {
        if (this.hasError()) {
            this.setError();
        } else {
            var url = appPath + 'Settings/Update';
            var input = {
                Name: this.name(),
                Tagline: this.tag(),
                UseImage: this.useImage(),
                ImageUrl: this.imageUrl(),
                GATrackingCode: this.ga(),
                CommentModeration: this.moderation(),
                PostCount: this.postCount(),
                Timezone: this.timezone(),
                Skin: this.skin(),
                LogFile: this.logFile(),
                LogLevel: this.logLevel,
                ShouldBackup: this.shouldBackup()
            };
            $.post(url, input, function (data) {
                if (data.Result) {
                    self.errorMessage('');
                    self.successMessage(data.Message);
                    // setTimeout(function () { self.successMessage(''); }, settings.fadeOutInterval);
                } else {
                    self.errorMessage(data.Message);
                    if (data.Errors) {
                        for (var idx = 0; idx < data.Errors.length; idx++)
                            self.errors.push(data.Errors[idx]);
                    }
                }
            });
        }
    }

    this.backup = function () {
        this.isBacking(true);
        $.get(this.backupUrl(), function (data) {
            self.isBacking(false);
            if (data.Result) {
                self.errorMessage('');
                self.backupMessage(data.Message);
                setTimeout(function () { self.backupMessage(''); }, settings.fadeOutInterval);
            } else {
                self.errorMessage(data.Message);
                if (data.Errors) {
                    for (var idx = 0; idx < data.Errors.length; idx++)
                        self.errors.push(data.Errors[idx]);
                }
            }
        });
    }

    this.generate = function () {
        // generate sitemap
        this.isGenerating(true);
        $.get(this.generateUrl(), function (data) {
            self.isGenerating(false);
            if (data.Result) {
                self.errorMessage('');
                self.generateMessage(data.Message);
                setTimeout(function () { self.generateMessage(''); }, settings.fadeOutInterval);
            } else {
                self.errorMessage(data.Message);
                if (data.Errors) {
                    for (var idx = 0; idx < data.Errors.length; idx++)
                        self.errors.push(data.Errors[idx]);
                }
            }
        });
    }

    this.getOptions = function (jsonArray) {
        var array = ko.observableArray();
        for (var idx = 0; idx < jsonArray.length; idx++) {
            var json = jsonArray[idx];
            array.push(new option(json.Id, json.Name));
        }
        return array();
    }
}